package com.ruoyi.common;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;

/**
 * Created by xiaoban on 2019/9/26.
 *
 */
@SuppressWarnings("deprecation")
public class CertUtil {
    //押金退还商户号
    //@Value("${wx-value.MCH_ID}")
    static private String MCH_ID = "1625789017";

    /**
     * 加载证书
     */
    public static SSLConnectionSocketFactory initCert() throws Exception {
        FileInputStream instream = null;
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        instream = new FileInputStream(new File("/nbiot/pfx/apiclient_cert.p12"));
        //instream = new FileInputStream(new File("E:\\天津充电桩\\1623453167_20220414_cert\\apiclient_cert.p12"));
        keyStore.load(instream, MCH_ID.toCharArray());

        if (null != instream) {
            instream.close();
        }

        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, MCH_ID.toCharArray()).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext,new String[] { "TLSv1","TLSv1.1","TLSv1.2"},null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

        return sslsf;
    }

    public static String HttpsPost(String url, String outputEntity) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        // 得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.setEntity(new StringEntity(outputEntity, "UTF-8"));
        // 加载含有证书的http请求
        HttpResponse response = HttpClients.custom().setSSLSocketFactory(CertUtil.initCert()).build().execute(httpPost);
        String result = EntityUtils.toString(response.getEntity(), "utf-8");
        return result;
    }
}
